﻿using System;
using NetAccess.Message;
using NetAccess.Server;

namespace SimpleChat.Network
{
    class ChatConnexion : ServerConnexion<Server>
    {
        public string Username { get; private set; }  

        protected override bool HandShake(object[] data)
        {
            if (data.Length < 2)
                return false;

            var password = (string)data[0];
            var username = (string)data[1];

            Server.MessengerInstance.Send(new ChatContentMessage(String.Format("Handshake ({0})", username), ChatContentMessage.MessageType.System));

            if (!Server.CheckPassword(password))
                return false;

            if (!Server.CheckUsername(username))
                return false;

            Username = username;

            return true;
        }

        protected override void OnConnected()
        {
            // refresh user list
            Send(new NetworkMessage(Contracts.NetworkMessageType.UserList, Server.GetAllUsers()));
            Broadcast(new NetworkMessage(Contracts.NetworkMessageType.UserConnect, Id, Username));
        }

        protected override void OnDisconnected()
        {
            // refresh user list
            Broadcast(new NetworkMessage(Contracts.NetworkMessageType.UserDisconnect, Id));
        }

        protected override void DataReceived(NetworkMessage message)
        {
            var mType = (Contracts.NetworkMessageType)message.MessageIdentifier;

            switch (mType)
            {
                case Contracts.NetworkMessageType.ChatMessage:
                    message.MessageData[0] = String.Format("[{0}] {1}", Username, message.MessageData[0]);
                    Send(message);
                    Broadcast(message);
                    break;
            }
        }

    }
}
